/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2024-03-19     weihui       the first version
 */

#include <bsp/bsp_spi2.h>
#include <drv_spi.h>
#include "spi_flash_sfud.h"
#include <fal.h>
#include <bsp/bsp_converter.h>

#define DBG_TAG "spi"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>



static const struct fal_partition *part_dev = NULL;
static uint8_t clc_arr[4]={0};
static int rt_hw_spi_flash_init(void)
{
    __HAL_RCC_GPIOB_CLK_ENABLE();
    rt_hw_spi_device_attach(SPI_BUS_NAME, W25Q_SPI_DEVICE_NAME, GPIOB, GPIO_PIN_12);


    if (RT_NULL == rt_sfud_flash_probe("W25Q128", W25Q_SPI_DEVICE_NAME))
    {
        return -RT_ERROR;
    };

    LOG_D("spi flash w25q128 initailize success.");

    fal_init();

    if((part_dev = fal_partition_find("easyflash")) != NULL)
    {
        LOG_D("easyflash dev find ok.");
    }
    return RT_EOK;
}
INIT_COMPONENT_EXPORT(rt_hw_spi_flash_init);


float_t nor_flash_float_read(uint32_t addr)
{
    fal_partition_read(part_dev,addr,clc_arr,4);
    if((clc_arr[0]==0xff)&&(clc_arr[1]==0xff)&&(clc_arr[2]==0xff)&&(clc_arr[3]==0xff))return 0xffffffff;
    else return bsp_cnv_arr_to_float(clc_arr,false);
}

int nor_flash_write(uint32_t addr,float_t value)
{
    bsp_cnv_float_to_arr(clc_arr,value,false);
    fal_partition_erase(part_dev,addr,4);
    return fal_partition_write(part_dev,addr,clc_arr,4);
}

